import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-05-30
 * Time: 22:28
 */
public class Test2 {
    public static void main(String[] args) throws SQLException {
        // 1. 创建数据源
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/jdbctest?characterEncoding=utf8&useSSL=false");
        dataSource.setUser("root");//账号
        dataSource.setPassword("111111");//密码

        // 2. 建立连接
        Connection connection = dataSource.getConnection();

        // 3. 构建 sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);

        // 4. 执行 sql, 这一步和前面不一样
        ResultSet resultSet = statement.executeQuery();//返回值是ResultSet,可以理解为数据集合
        // 5. 遍历结果集合
        while (resultSet.next()) {
            // 循环里针对一行进行处理
            System.out.println(resultSet.getInt("id") + "\t" + resultSet.getString("name"));
        }
        // 6. 关闭对应的资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}
